﻿using System;
using System.IO;
using System.Text;


namespace HAVNet.Core.IO
{
    public delegate bool DirWalkerOnFound (string path, int depth, bool isDir, bool err);

    public class Dirs
    {
        public static string getExeDir ()
        {
            return System.IO.Path.GetDirectoryName (
                System.Reflection.Assembly.GetExecutingAssembly().GetModules()[0].FullyQualifiedName
            );
        }

        public static void walk (string dir, string wildCards, int depth, DirWalkerOnFound onFound)
        {
            walk (dir, wildCards, depth, onFound, null); // is not recursion, is and overloaded function. Ale.
        }

        public static void walk (string dir, string wildCards, int depth, DirWalkerOnFound onFound, object ioLock)
        {
            bool        err     = false;
            string []   files   = null;
            string []   dirs    = null;

            try
            {
                if (ioLock != null)
                {
                    lock (ioLock)
                    {
                        files   = Directory.GetFiles        (dir, wildCards);
                        dirs    = Directory.GetDirectories  (dir);
                    }
                }
                else
                {
                    files   = Directory.GetFiles        (dir, wildCards);
                    dirs    = Directory.GetDirectories  (dir);
                }
            }
            catch
            {
                err = true;
            }

            if (! onFound (dir, depth + 1, true, err))
                return;

            if (err)
                return;

            foreach (string fileX in files)
                if (! onFound (fileX, depth + 1, false, false))
                    break;

            foreach (string dirX in dirs)
                walk(dirX, wildCards, depth + 1, onFound, ioLock);
        }
    }
}
